# coding=utf-8
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from models import UserInfo
from hashlib import sha1


def register(request):
    return render(request, "df_user/register.html")


def handle_register(request):
    post = request.POST
    name = post.get('user_name')
    pwd = post.get('pwd')
    cpwd = post.get('cpwd')
    email = post.get('email')

    # 密码加密
    s = sha1()
    s.update(pwd)
    save_pwd = s.hexdigest()

    user = UserInfo()
    user.name = name
    user.email = email
    user.psd = save_pwd

    user.save()
    return redirect('/login/')


def register_exist(request):
    name = request.GET.get('name')
    print("name:" + name)
    count = UserInfo.objects.filter(name=name).count()
    return JsonResponse({'count': count})


def user_login(request):
    name = request.COOKIES.get('name', '')
    context = {'title': '用户登录', 'error_name': 0, 'error_pwd': 0, 'name': name}
    return render(request, "df_user/login.html", context)


def login_handle(request):
    post = request.POST
    name = post.get('username')
    pwd = post.get('pwd')
    jizhu = post.get('jizhu', 0)

    users = UserInfo.objects.filter(name=name)

    if len(users) == 1:
        s1 = sha1()
        s1.update(pwd)
        if s1.hexdigest() == users[0].psd:
            red = HttpResponseRedirect('/user/info/')
            # 记住用户名
            if jizhu != 0:
                red.set_cookie('name', name)
            else:
                red.set_cookie('name', '', max_age=-1)
            request.session['user_id'] = users[0].id
            request.session['user_name'] = name
            return red
        else:
            context = {'title': '用户登录', 'error_name': 0, 'error_pwd': 1, 'name': name, 'pwd': pwd}
            return render(request, 'df_user/login.html', context)
    else:
        context = {'title': '用户登录', 'error_name': 1, 'error_pwd': 0, 'name': name, 'pwd': pwd}
        return render(request, 'df_user/login.html', context)
